package com.hj.dapp.config.security;

import com.hj.dapp.business.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Collections;


/**
 * @author 胡奥程
 * @version 1.0
 * @date 2023/12/29
 */

@Configuration
public class WebSecurityConfig {
    @Autowired
    private UserService userService;
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    private String[] loadExcludePath() {
        return new String[]{
                "/static/**",
                "/templates/**",
                "/img/**",
                "/js/**",
                "/css/**",
                "/lib/**",
                "/swagger-ui.html",
                "/swagger-ui/index.html",
                "/swagger-ui/**",
                "/swagger-resources/**",
                "/v2/api-docs/**",
                "/v3/api-docs/**",
                "/bus/v3/api-docs/**",
                "/api-docs/**",
                "/webjars/**",
                "/budget/exportLightAuxiliary/**",
                "/mainbudget/exportMainBudget/**"
        };
    }
    private String[] loadPath() {
        return new String[]{
                "/user/deleteUser/**",
                "/user/getUserList",
                "/user/pageUser",
                "/menu/saveMenu",
                "/oss/fileUpload",
                "/ocr/getIdCardInfo",
                "/sign/signContact",
                "/budget/exportLightAuxiliary"
        };
    }

    @Bean
    AuthenticationManager authenticationManager(HttpSecurity httpSecurity, PasswordEncoder passwordEncoder) throws Exception {
        AuthenticationManager authenticationManager = httpSecurity.getSharedObject(AuthenticationManagerBuilder.class)
                .userDetailsService(userService)
                .passwordEncoder(passwordEncoder)
                .and()
                .build();
        return authenticationManager;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity, AuthenticationManager authenticationManager, UserService userService) throws Exception {
        httpSecurity.csrf().disable()
                .cors().configurationSource(corsConfigSource()).and()
                .authorizeRequests()
                //放通所有静态资源
                .antMatchers(loadExcludePath()).permitAll()
                //放通注册
                .antMatchers(HttpMethod.PUT, "/user/registerUser").permitAll()
                .antMatchers(loadPath()).access("isAuthenticated() and @rbacService.hasPermission(request,authentication)")
                //其余请求都需要认证后访问
                .anyRequest()
                .authenticated()
                .and()
                .addFilterBefore(new JwtLoginFilter(authenticationManager), UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(new JwtVerifyFilter(userService), UsernamePasswordAuthenticationFilter.class)
                .exceptionHandling().accessDeniedHandler(new UserAuthAccessDeniedHandler()).and()
                .exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint())
                .and()
                //关闭session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        return httpSecurity.build();

    }
    private CorsConfigurationSource corsConfigSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        configuration.setAllowedOrigins(Collections.singletonList("*"));
        configuration.setAllowedMethods(Collections.singletonList("*"));
        configuration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

}
